package org.example.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

/**
 * @Auther:Liu
 * @Testname:SentinelBlockExceptionHandler
 * @Date:2025/9/15 10:18
 */
//@Component
public class SentinelBlockExceptionHandler  implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest req, HttpServletResponse resp, BlockException e) throws Exception {
        // BlockException 异常接⼝,包含Sentinel的五个异常
        // FlowException 限流异常
        // DegradeException 降级异常
        // ParamFlowException 参数限流异常
        // AuthorityException 授权异常
        // SystemBlockException 系统负载异常
        String result = "";
        if (e instanceof FlowException) {
            result = "流量被限制了";
        } else if (e instanceof DegradeException) {
            result = "服务被降级了";
        } else if (e instanceof ParamFlowException) {
            result = "参数异常";
        } else if (e instanceof AuthorityException) {
            result = "未经授权";
        } else {
            result = "其他异常";
        }
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println(result);

    }
}
